import * as vscode from 'vscode';
import { VerticalDiffManager } from '../../../src/diff/vertical/manager';
import { LLMFactory } from '../../../core/llm/llmFactory';
import * as fs from 'fs';
import * as path from 'path';
import { APIData } from './Service/ApiLocation';

export class ApiPanelProvider implements vscode.WebviewViewProvider {
    private _context: vscode.ExtensionContext;
    private _verticalDiffManager: VerticalDiffManager;
    private _llmFactory: LLMFactory;
    private _view?: vscode.WebviewView;
    private _data: APIData[] = [];
    private _onDidChangeData = new vscode.EventEmitter<void>();

    constructor(
        context: vscode.ExtensionContext,
        verticalDiffManager: VerticalDiffManager,
        llmFactory: LLMFactory,
    ) {
        this._context = context;
        this._verticalDiffManager = verticalDiffManager;
        this._llmFactory = llmFactory;
    }

    // 跳转到指定文件和行号的函数
    private async navigateToFileAndLine(data: APIData) {
        try {
            const document = await vscode.workspace.openTextDocument(vscode.Uri.file(data.filePath));
            const editor = await vscode.window.showTextDocument(document);

            const totalLines = document.lineCount;
            const line = Number(data.line)-1; // 确保行号是数字
            if (line > 0 && line <= totalLines) {
                const position = new vscode.Position(line, 0);
                const range = new vscode.Range(position, position);
                editor.revealRange(range, vscode.TextEditorRevealType.InCenter);
                editor.selection = new vscode.Selection(position, position);

                // 调用装饰器
                vscode.commands.executeCommand('HarmonyPilot.decorateLine', data); // 行号从 0 开始            
            } else {
                vscode.window.showErrorMessage(`行号 ${data.line} 无效，请输入 1 到 ${totalLines} 之间的行号。`);
            }
        } catch (error) {
            const errorMessage = error instanceof Error ? error.message : String(error);
            vscode.window.showErrorMessage(`无法打开文件 ${data.filePath}：${errorMessage}`);
        }
    }
    private getRange(stratLine0:number, endLine0:number): vscode.Range {
        const startLine = Math.min(stratLine0, endLine0);
        const endLine = Math.max(stratLine0, endLine0);
        return new vscode.Range(startLine, 0, endLine, Number.MAX_SAFE_INTEGER);
    }
    resolveWebviewView(
        webviewView: vscode.WebviewView,
        context: vscode.WebviewViewResolveContext,
        token: vscode.CancellationToken
    ) {
        this._view = webviewView;
        webviewView.webview.options = {
            enableScripts: true, // 允许运行脚本
        };

        // 初始化 Webview 内容
        this.updateWebviewContent();

        // 监听 Webview 消息
        webviewView.webview.onDidReceiveMessage(async message => {
            if (message.command === 'navigateToFileAndLineByIndex') {
                const { index } = message;
                const item = this._data[index];
                if (item) {
                    await this.navigateToFileAndLine(item);
                } else {
                    vscode.window.showErrorMessage('无效的索引，无法跳转到指定位置。');
                }
            } else if (message.command === 'fixCodeByIndex') {
                const { index } = message;
                const item = this._data[index];
                if (item) {
                    await this.navigateToFileAndLine(item);
                    vscode.commands.executeCommand('HarmonyPilot.fixCode', item); // 行号从 0 开始
                } else {
                    vscode.window.showErrorMessage('无效的索引，无法修复代码。');
                }
            }
        });

        // 监听数据变化
        this._onDidChangeData.event(() => {
            this.updateWebviewContent();
        });
    }

    updateData(newData: APIData[]) {
        this._data = newData;
        this._onDidChangeData.fire();
    }

    private updateWebviewContent() {
        if (!this._view) {
            console.error('Webview is not initialized.');
            return;
        }

        const htmlFilePath = path.join(this._context.extensionPath, 'plugins', 'actions', 'ApiPilot', 'webviewContent.html');
        try {
            const htmlContent = fs.readFileSync(htmlFilePath, 'utf-8');
            const rows = this._data.map((item, index) => {
                const workspaceFolder = vscode.workspace.workspaceFolders?.[0]?.uri.fsPath;
                const relativePath = path.relative(workspaceFolder || '', item.filePath);

                return `
                    <tr>
                        <td>${item.api}</td>
                        <td onclick="handleRowClick(${index})">${relativePath}:${item.line}</td>
                        <td><a href="${item.guide}" target="_blank">查看指导</a></td>
                        <td><button onclick="handleFixClick(${index})">修复</button></td>
                    </tr>
                `;
            }).join('');

            this._view.webview.html = htmlContent.replace('{{rows}}', rows);
        } catch (error) {
            console.error('Failed to load HTML content:', error);
        }
    }
}